package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsTaskService taskService;


    /**
     * 根据条件查询文章的分页数据
     * @return
     */
    @Override
    public ResponseResult findPage(WmNewsPageReqDto dto) {
        //1.校验参数
        if (null == dto){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        dto.checkParam();
        //2.构建查询条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //状态查询
        if (null != dto.getStatus()){
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //频道查询
        if (null != dto.getChannelId()){
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //开始与结束时间查询
        if (null != dto.getBeginPubDate() && null != dto.getEndPubDate()){
            lambdaQueryWrapper.between(WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //关键字模糊查询
        if (null != dto.getKeyword()){
            lambdaQueryWrapper.like(WmNews::getTitle, "%" + dto.getKeyword() + "%");
        }
        //查询登录用户的文章
        lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.get().getId());

        //发布时间（倒叙）
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);


        //3.构建分页参数

        IPage<WmNews> page = new Page(dto.getPage(), dto.getSize());
        //4.查询
         page = page(page, lambdaQueryWrapper);
        //5.返回分页结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());

        pageResponseResult.setData(page.getRecords());

        return pageResponseResult;
    }

    /**
     * 发布文章或者保存草稿
     * @param dto
     * @return
     * @throws Exception
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        //1.数据的校验
        if (null == dto || StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.保存或者更新文章的数据
        WmNews wmNews = saveOrUpdateNews(dto);
        //3.判断文章提交是否是直接提交还是保存草稿，如果是保存草稿则直接返回
        if (dto.getStatus() == 0){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //4.从内容中抽取图片
        List<String> imageUrls = ectractUrlInfo(dto.getContent());
        //5.批量保存内容中的图片和素材的关系
        saveRelativeInfoForContent(imageUrls,wmNews.getId());
        //6.保存封面图片和素材之间的关系（封面如果是自动则需要自己按照规则匹配图片，然后保存）
        saveRelativeInfoForCover(dto.getImages(),imageUrls,wmNews,dto.getType());
        //7.审核文章
        //wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        taskService.addWmNewsToTask(wmNews);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面图片和素材之间的关系
     * @param images
     * @param imageUrls
     * @param wmNews
     * 文章封面类型  0 无图 1 单图 3 多图 -1 自动
     */
    private void saveRelativeInfoForCover(List<String> images, List<String> imageUrls, WmNews wmNews,Short type) {
        if (type == -1){
            if (null == imageUrls || imageUrls.size() == 0){
                //设置文章类型为无图
                wmNews.setType((short)0);
            }else if (imageUrls.size() < 3){
                //抽取一个图片作为封面
                images.add(imageUrls.get(0));
                wmNews.setType((short)1);
            }else {
                images.addAll(imageUrls.stream().limit(3).collect(Collectors.toList()));
                wmNews.setType((short)3);
            }
            //更新文章的类型
            updateById(wmNews);

            //无图则不再走下面的逻辑
            if (null != images && images.size() > 0){
                //图片里面可能存在相同的图片，需要去重
                saveRelativeInfo(images, wmNews.getId(),(byte) 1);
            }
        }
    }

    /**
     * 批量保存内容中的图片和素材的关系
     * @param imageUrls
     * @param id
     */
    private void saveRelativeInfoForContent(List<String> imageUrls, Integer id) {
        saveRelativeInfo(imageUrls, id,(byte) 0);
    }


    private void saveRelativeInfo(List<String> imageUrls, Integer wmNewsid,byte type) {
        //数据校验
        if(null == imageUrls || imageUrls.size() == 0){
            return;
        }
        //图片里面可能存在相同的图片，需要去重
        imageUrls = imageUrls.stream().distinct().collect(Collectors.toList());

        //通过图片的地址来查询图片的id
        List<WmMaterial> list = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageUrls));

        //判断数据是否被删除过了
        if (null == list || list.size() != imageUrls.size()) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //通过素材得到素材的id
        /*List<Integer> materialIds = new ArrayList<>();
        for (Integer materialId : materialIds) {
            materialIds.add(materialId);
        }*/
        List<Integer> materialIds = list.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());

        wmNewsMaterialMapper.batchInsert(materialIds, wmNewsid, type);
    }

    /**
     * 抽取文章内容中的图片
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {

        List<Map> list = JSON.parseArray(content, Map.class);

        ArrayList<String> result = new ArrayList<>();
        if (null != list && list.size() > 0){
            for (Map map : list) {
                if ("image".equals(map.get("type"))){
                    result.add(map.get("value").toString());
                }
            }
        }
        return result;
    }

    /**
     * 保存或者更新文章数据
     */

    private WmNews saveOrUpdateNews(WmNewsDto dto){
        WmNews wmNews = new WmNews();
        //把dto中的数据拷贝到wmNews对象
        //1.两个对象的属性名称必须一样
        //2.两个对象的属性类型必须一样
        BeanUtils.copyProperties(dto,wmNews);

        WmUser wmUser = WmThreadLocalUtil.get();

        //设置用户id
        if(null == wmUser){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        wmNews.setUserId(wmUser.getId());

        //封面图片数据拷贝不会成功需要将List->string
        if (dto.getImages() != null && dto.getImages().size() > 0){
            String images = StringUtils.join(dto.getImages().toArray(), ",");
            wmNews.setImages(images);
        }
        //如果类型是无图，数据无法储存到数据库，需要把数据设置为null
        if(dto.getType() == -1){
            wmNews.setType(null);
        }

        //判断dto中是否有id，如果有则直接更新，如果没有就新增
        if (null == dto.getId()){
            //直接保存
            save(wmNews);
        }else {
            //删除关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,dto.getId()));
            //更新
            updateById(wmNews);
        }
        return wmNews;
    }
}
